import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import { Modal, Button, Select, Input, Radio, Icon, InputNumber, message } from 'antd';
import { transferOption } from '@/support/utils';

let id = 3;
let initialKeys = [0, 1, 2];
const typeList = [
  {
    value: 1,
    label: '文本',
  },
  {
    value: 2,
    label: '下拉列表',
  },
  {
    value: 3,
    label: '数字',
  },
  {
    value: 4,
    label: '日期',
  },
  {
    value: 5,
    label: '时间',
  },
  {
    value: 6,
    label: '日期时间',
  },
  {
    value: 7,
    label: 'URL链接',
  },
];
@connect((state) => ({
  fieldSetting: state.fieldSetting,
}))
@Form.create()
export default class AddFieldModal extends PureComponent {
  constructor(props) {
    super(props);
    const { dispatch, form } = props;
    this.state = {
      loading: false,
      selectedType: props.formData?.type,
      selectSuffixText: '',
      uuid: props.formData?.uuid,
      option: {},
      optionList: [],
    };
  }

  componentDidMount() {
    setTimeout(() => {
      const { formData, form } = this.props;
      const { groupId, name, type } = formData;
      form.setFieldsValue({
        groupId,
        name,
        type: type ? type + '' : null,
      });
      if (formData.type == 2) {
        const data = JSON.parse(formData.extra || '{}');
        form.setFieldsValue({
          selectType: data.selectType,
        });
        this.setState({
          option: Object.fromEntries(data.optionList.map((item) => [item, item])),
          optionList: data.optionList,
        });
      } else if (formData.type == 3) {
        const data = JSON.parse(formData.extra || '{}');
        form.setFieldsValue(
          {
            digit: data,
          },
          () => {
            this.setState({
              selectSuffixText: `1024.${[...Array(form.getFieldValue('digit'))]
                .map((i) => 0)
                .join('')}`,
            });
          },
        );
      } else if (formData.type == 4) {
        this.setState({
          selectSuffixText: '2022-01-01',
        });
      } else if (formData.type == 5) {
        this.setState({
          selectSuffixText: '23:59:59',
        });
      } else if (formData.type == 6) {
        this.setState({
          selectSuffixText: '2022-01-01 23:59:59',
        });
      }
    }, 300);
  }
  onTypeSelect = (e) => {
    console.log(e);
    const { form } = this.props;
    this.setState({
      selectSuffixText: '',
    });
    e == 2 &&
      form.setFieldsValue({
        optionList: initialKeys,
      });
    if (e == 3) {
      setTimeout(() => {
        form.setFieldsValue(
          {
            digit: 2,
          },
          () => {
            this.setState({
              selectSuffixText: `1024.${[...Array(form.getFieldValue('digit'))]
                .map((i) => 0)
                .join('')}`,
            });
          },
        );
      }, 300);
    } else if (e == 4) {
      this.setState({
        selectSuffixText: '2022-01-01',
      });
    } else if (e == 5) {
      this.setState({
        selectSuffixText: '23:59:59',
      });
    } else if (e == 6) {
      this.setState({
        selectSuffixText: '2022-01-01 23:59:59',
      });
    }

    this.setState({
      selectedType: e,
    });
  };
  removeField = (k) => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('optionList');
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      optionList: keys.filter((key) => key !== k),
    });
  };

  addField = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue('optionList');
    const nextKeys = keys.concat(id++);
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      optionList: nextKeys,
    });
  };

  handleSubmit = () => {
    const { form, changeVisible, dispatch } = this.props;
    const { selectedType, uuid } = this.state;
    form.validateFields((err, values) => {
      if (err) return;
      // console.log(values);
      const { groupId, name, type } = values;
      const params = {
        uuid,
        groupId,
        name,
        type,
      };
      if (selectedType == 3) {
        params.digit = values.digit;
      } else if (selectedType == 2) {
        params.selectType = values.selectType;
        params.optionList = Object.values(values.option).filter((i) => !!i);
      }
      // console.log(params);
      // changeVisible();
      dispatch({
        type: 'fieldSetting/fieldSettingSave',
        payload: {
          url: '/mscreditbusiness/credit/field/setting/save',
          ...params,
        },
        callback: (response) => {
          if (response && response.statusCode == '0') {
            // console.log('success', response);
            message.success('保存成功');
            changeVisible();
          } else {
            message.error(response.statusMessage);
          }
        },
      });
    });
  };
  render() {
    const {
      fieldSetting: { modalLoading, groupList, fieldCount },
      form: { getFieldDecorator, getFieldValue },
      visible,
      changeVisible,
    } = this.props;
    const { selectedType, selectSuffixText, uuid } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 16, offset: 6 },
      },
    };
    getFieldDecorator('optionList', {
      initialValue: !uuid ? initialKeys : this.state.optionList,
    });
    const keys = getFieldValue('optionList');
    const formItems =
      keys &&
      keys?.map((k, index) => (
        <Form.Item {...formItemLayoutWithOutLabel} key={k}>
          {getFieldDecorator(`option[${k}]`, {
            validateTrigger: ['onChange', 'onBlur'],
            rules: [
              {
                required: selectedType == 2,
                whitespace: true,
                message: '请输入选项',
              },
            ],
            initialValue: this.state.option[k] || '',
          })(<Input placeholder="请输入选项" style={{ width: '60%', marginRight: 8 }} />)}
          {keys.length > 1 ? (
            <Button type="primary" onClick={() => this.removeField(k)}>
              删除
            </Button>
          ) : null}
        </Form.Item>
      ));
    return (
      <Modal
        title={`${!uuid ? '新增' : '编辑'}字段(${fieldCount}/100)`}
        style={{ top: 20 }}
        width="40%"
        visible={visible}
        closable={false}
        maskClosable={false}
        onCancel={() => changeVisible()}
        footer={[
          <Button key="back" size="small" onClick={() => changeVisible()}>
            取消
          </Button>,

          <Button
            key="submit"
            type="primary"
            size="small"
            // loading={loading}
            onClick={this.handleSubmit}
          >
            保存
          </Button>,
        ]}
      >
        <Form>
          <Form.Item {...formItemLayout} label="字段分组">
            {getFieldDecorator('groupId', {
              rules: [
                {
                  required: true,
                  message: '请选择',
                },
              ],
            })(
              <Select
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                placeholder="请选择"
                onChange={this.onAreaSelect}
                disabled={!!uuid}
              >
                {transferOption(groupList, ['uuid', 'name'])}
              </Select>,
            )}
          </Form.Item>
          <Form.Item {...formItemLayout} label="字段名称">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '请填写',
                },
              ],
            })(<Input placeholder="请填写" maxLength={32} allowClear disabled={!!uuid} />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="字段类型">
            {getFieldDecorator('type', {
              rules: [
                {
                  required: true,
                  message: '请选择',
                },
              ],
            })(
              <Select
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                placeholder="请选择"
                onChange={this.onTypeSelect}
                // disabled={}
                suffixIcon={
                  <>
                    <span
                      style={{
                        color: 'rgba(0,0,0,.25)',
                        lineHeight: '12px',
                        height: '12px',
                        display: 'inline-block',
                        marginRight: '5px',
                      }}
                    >
                      {selectSuffixText}
                    </span>
                    <Icon type="down" />
                  </>
                }
              >
                {transferOption(typeList)}
              </Select>,
            )}
          </Form.Item>
          {/* 下拉列表 */}
          {selectedType == 2 && (
            <>
              <Form.Item {...formItemLayoutWithOutLabel}>
                {getFieldDecorator('selectType', {
                  rules: [
                    {
                      required: true,
                      message: '请选择',
                    },
                  ],
                })(
                  <Radio.Group>
                    <Radio value={0}>单选</Radio>
                    <Radio value={1}>多选</Radio>
                  </Radio.Group>,
                )}
              </Form.Item>
              {formItems}
              <Form.Item {...formItemLayoutWithOutLabel}>
                <Button type="primary" onClick={this.addField} style={{ width: '60%' }}>
                  <Icon type="plus" /> 新增选项
                </Button>
              </Form.Item>
            </>
          )}
          {/* 数字 */}
          {selectedType == 3 && (
            <>
              <Form.Item
                labelCol={{
                  xs: { span: 24, offset: 0 },
                  sm: { span: 3, offset: 6 },
                }}
                wrapperCol={{
                  xs: { span: 24 },
                  sm: { span: 6 },
                }}
                label="小数位数"
                required={false}
              >
                {getFieldDecorator('digit', {
                  rules: [
                    {
                      required: true,
                      message: '请输入',
                    },
                  ],
                  initialValue: 2,
                })(
                  <InputNumber
                    min={0}
                    max={4}
                    style={{ width: 150 }}
                    onChange={(e) => {
                      this.setState({
                        selectSuffixText: !!e
                          ? `1024.${[...Array(e)].map((i) => 0).join('')}`
                          : '1024',
                      });
                    }}
                  />,
                )}
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    );
  }
}
